package com.abc.recycling.service.impl;

import com.abc.recycling.model.NotificationTemplate;
import com.abc.recycling.repository.NotificationTemplateRepository;
import com.abc.recycling.service.NotificationTemplateService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class NotificationTemplateServiceImpl implements NotificationTemplateService {

    private final NotificationTemplateRepository notificationTemplateRepository;

    @Override
    @Transactional
    public NotificationTemplate createTemplate(NotificationTemplate template) {
        template.setCreateTime(LocalDateTime.now());
        template.setUpdateTime(LocalDateTime.now());
        return notificationTemplateRepository.save(template);
    }

    @Override
    @Transactional
    public NotificationTemplate updateTemplate(NotificationTemplate template) {
        NotificationTemplate existingTemplate = notificationTemplateRepository.findById(template.getId())
                .orElseThrow(() -> new RuntimeException("模板不存在"));
        
        template.setUpdateTime(LocalDateTime.now());
        return notificationTemplateRepository.save(template);
    }

    @Override
    @Transactional
    public void deleteTemplate(Long id) {
        notificationTemplateRepository.deleteById(id);
    }

    @Override
    public NotificationTemplate getTemplateById(Long id) {
        return notificationTemplateRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("模板不存在"));
    }

    @Override
    public NotificationTemplate getTemplateByCode(String code) {
        return notificationTemplateRepository.findByCode(code)
                .orElseThrow(() -> new RuntimeException("模板不存在"));
    }

    @Override
    public List<NotificationTemplate> getAllTemplates() {
        return notificationTemplateRepository.findAll();
    }

    @Override
    public Page<NotificationTemplate> getTemplatesByPage(Pageable pageable) {
        return notificationTemplateRepository.findAll(pageable);
    }

    @Override
    public List<NotificationTemplate> getTemplatesByType(String type) {
        return notificationTemplateRepository.findByType(type);
    }

    @Override
    public String processTemplate(String templateCode, Object data) {
        NotificationTemplate template = getTemplateByCode(templateCode);
        // TODO: 实现模板处理逻辑
        return template.getContent();
    }
} 